// This file estimates Total Factor Productivity by firm-year


ssc install prodest    // command for structural estimation
ssc install gtools

use "$in/admin3_nav_eredeti.dta", clear

// Generate variables

gen Y = cond(missing(ranyag03), arbevert, arbevert-ranyag03)
egen M = rowtotal(ranyag01 ranyag02), missing
egen K = rowtotal(jetok??), missing    
gen L = letszam
gen VA = Y-M

foreach v of any Y M K L VA {
	gen ln`v' = ln(`v')
	}

xtset vallazon ev

// Estimation

* Wooldridge
xi: prodest lnVA, free(lnL) proxy(lnM) state(lnK) met(wrdg) va control(i.ev)
predict tfp_wr, resid
lab var tfp_wr "ln TFP, Wooldridge on value added"

// Save TFPs
keep vallazon ev tfp_wr
sort vallazon ev
by vallazon, sort: egen mean_tfp_wr=mean(tfp_wr)

save "$out/tfp.dta", replace


***************Further indicators*****************


*Ownership

use anon ev kor w vallazon1 w1 wh1 if  kor<=70 & kor>=18 using "$in/admin3_alap.dta" , clear
rename vallazon1 vallazon

merge m:1 vallazon ev using "$in/admin3_nav_eredeti.dta", nogen keep(master match) keepusing(letszam jetok*)

gen jetok=0 if letszam~=.
foreach var of varlist jetok01 jetok02 jetok03 jetok04 jetok05 jetok06 jetok07 jetok08 jetok011 {
 
replace `var'=0 if `var'==.
replace jetok=jetok+`var'

}
gen foreign_share=jetok06/jetok

gen FO=0 if foreign_share~=.
replace FO=1 if foreign_share>0.5 & foreign_share~=.

*Mean wage

cap drop w_adj
gen w_adj=w1/wh1*40

by vallazon ev, sort: egen mean_firmw=mean(w_adj)

collapse (mean) letszam mean_firmw FO, by(vallazon ev)
compress

merge 1:1 vallazon ev using "$out/tfp.dta", nogen
compress
save "$out/firmquality.dta", replace

